package com.sparrow.socket.tcp.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TcpIdleStateHandler extends ChannelInboundHandlerAdapter {
    private static Logger logger = LoggerFactory.getLogger(TcpIdleStateHandler.class);

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent ise = (IdleStateEvent) evt;
            if (ise.state().equals(IdleState.READER_IDLE)) {
                logger.info("connect READER_IDLE, closing. {}", ctx);
                ctx.close();
            } else if (ise.state().equals(IdleState.WRITER_IDLE)) {
                logger.info("connect WRITER_IDLE, closing. {}", ctx);
                ctx.close();
            }
        }
    }
}
